﻿using Microsoft.Extensions.Hosting;
using Solution.Core.Repository;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Solution.Application.Workers
{
    public class RedisWorker : BackgroundService
    {
        private readonly IRedisSingletoneClient _redisClient;

        public RedisWorker(IRedisSingletoneClient redisSingletoneClient)
        {
            _redisClient = redisSingletoneClient;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine("add test key to db 0:");
            await _redisClient.AddAsync("test", "test");

            Console.WriteLine("get test key from db 0:");
            var value = await _redisClient.GetAsync<string>("test");
            Console.WriteLine($"key 'test' value is : {value}");

            await LockAsync();
        }

        private async Task LockAsync()
        {
            string key = Guid.NewGuid().ToString();
            await _redisClient.Lock(key, 10);
            int retry = 0;
            bool tryLock = false;
            while (!tryLock)
            {
                tryLock = await _redisClient.Lock(key, 5, 0);
                retry++;
                Console.WriteLine($"retry tryLock {key} {retry} times {tryLock}");
                Thread.Sleep(1000);
            }
        }
    }
}